package com.wudl.queue.config;

import com.wudl.queue.domain.User;
import com.wudl.queue.service.UserService;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author ：wudl
 * @date ：Created in 2021-12-12 22:26
 * @description：
 * @modified By：
 * @version: 1.0
 */

@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
@Component
public class UserConsume  {

    @Autowired
    UserService userService;

    List<User> list = new LinkedList<>();
    int number = 0;
    public synchronized   void run() throws Exception {


        while (true) {
            User consume = null;
            try {
                consume = ApplicationQueue.getMailQueue().consume();

                FileWriter fw = new FileWriter("D:\\tmp\\CCCC.txt", true);
                BufferedWriter bw = new BufferedWriter(fw);

                bw.append("消费-->");
                bw.write(consume.toString() + "\r\n ");
                bw.close();
                fw.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        list.add(consume);
        if (list.size() >=10)
        {

            List<User> strsSync = Collections.synchronizedList(list);


            userService.insertBatch(strsSync);
            System.out.println(list.size());
            list.clear();
        }
        }
    }

    private static String lock = "";
    @Synchronized
    @Scheduled(fixedDelay = 100)  //间隔1秒
    public void cleanRankListJobExecute() throws Exception {

        User  consume = ApplicationQueue.getMailQueue().consume();

        MyAppThreadFactory.myCachedThreadPool.execute(()->
        {

        });
        try {
            synchronized (lock){
                run();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
